package cn.growthgate.fgo.web;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.entity.Class;
import cn.growthgate.fgo.entity.ClassIntermediary;
import cn.growthgate.fgo.service.IClassIntermediaryService;
import cn.growthgate.fgo.service.IClassService;
import cn.growthgate.fgo.web.result.JsonResult;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author GrowthGate
 * @since 2019-01-20
 */
@Controller
@RequestMapping("/classIntermediary")
@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
public class ClassIntermediaryController {

	@Autowired
	private IClassIntermediaryService classIntermediaryService;

	@Autowired
	private IClassService classService;

	@RequestMapping("/list")
	public ModelAndView list() {
		List<Class> classes = classService.selectAll();
		// 获取职介相性数据
		List<ClassIntermediary> classIntermediaries = classIntermediaryService.selectAll();
		Map<Long, Map<Long, BigDecimal>> classIntermediaryMap = classes.stream()
				.collect(Collectors.toMap(Class::getId, entity -> new HashMap<>()));
		for (ClassIntermediary classIntermediary : classIntermediaries) {
			Map<Long, BigDecimal> map = classIntermediaryMap.get(classIntermediary.getAttackerId());
			map.put(classIntermediary.getDefenderId(), classIntermediary.getDamage());
		}

		return new ModelAndView("classIntermediary/list").addObject("classes", classes)
				.addObject("classIntermediaryMap", classIntermediaryMap);
	}

	@ResponseBody
	@RequestMapping("/save")
	public JsonResult save(@Validated ClassIntermediary classIntermediary, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return JsonResult.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		// 数据库中是否存在
		ClassIntermediary oClassIntermediary = classIntermediaryService.get(classIntermediary.getAttackerId(),
				classIntermediary.getDefenderId());
		if (oClassIntermediary != null) {
			oClassIntermediary.setDamage(classIntermediary.getDamage());
		} else {
			oClassIntermediary = classIntermediary;
		}
		classIntermediaryService.insertOrUpdate(oClassIntermediary);
		return JsonResult.ok("保存成功");
	}

}
